package com.tianyadu.mmall.core.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.HashSet;
import java.util.Set;

/**
 * 实体属性拷贝，过来非空信息
 *
 * @author xueyj
 * @date 2019-10-28 15:47
 */
public class BeanUtil {
    /**
     * 拷贝非空属性值
     *
     * @param src
     * @param target
     * @return void
     * @author xueyj
     * @date 2019/10/28-15:48
     */
    public static void copyPropertiesIgnoreNull(Object src, Object target) {
        BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
    }

    /**
     * 获取空属性名称
     *
     * @param source
     * @return java.lang.String[]
     * @author xueyj
     * @date 2019/10/28-15:48
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}